//
//  ThreePriceViewController.m
//  XDCommonApp
//
//  Created by xindao on 14-7-2.
//  Copyright (c) 2014年 XD-XY. All rights reserved.
//

#import "ThreePriceViewController.h"
#import "LoginViewController.h"
@interface ThreePriceViewController ()

@end

@implementation ThreePriceViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

//- (void)viewWillAppear:(BOOL)animated{
//    [super viewWillAppear:YES];
//    [headIV closeTimerTask];
//}

- (void)viewDidLoad
{
    [super viewDidLoad];

    dataArray = [[NSMutableArray alloc] init];
    btnArray = [[NSMutableArray alloc] init];

    self.titleLabel.text = @"支付";

    int height = 0;
    if (IOS7) {
        height = 20;
    }
    UIImageView * shareIV = [[UIImageView alloc] initWithFrame:CGRectMake(285, height+10, 25, 25)];
    shareIV.image = [UIImage imageNamed:@"shareBtn_img"];
    [self.navigationBarView addSubview:shareIV];

    [XDTools getAButtonForView:self.navigationBarView frame:CGRectMake(270, height, 50, 44) nomalTitle:nil hlTitle:nil titleColor:nil bgColor:[UIColor clearColor] nbgImage:nil hbgImage:nil action:@selector(shareBtnClick) target:self buttonTpye:UIButtonTypeCustom];


    UIScrollView * backScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_MAINSCREEN_HEIGHT)];
    backScrollView.contentSize = CGSizeMake(UI_SCREEN_WIDTH, 542);
    [self.contentView addSubview:backScrollView];

    headIV = [[XYScrollView alloc] initPageScrollView:CGRectMake(0, 0, UI_SCREEN_WIDTH, 285) pageControllerFrame:CGRectMake(0, 265, 320, 20) backgroudImage:nil pageNumber:3];
    headIV.userInteractionEnabled = YES;
    headIV.isRunning = NO;
    [backScrollView addSubview:headIV];

    bgView2 = [[UIView alloc] initWithFrame:CGRectMake(0, 285, UI_SCREEN_WIDTH, UI_MAINSCREEN_HEIGHT - 285 - UI_NAVIGATION_BAR_HEIGHT)];
    [backScrollView addSubview:bgView2];

    UILabel * titleLB = [[UILabel alloc] initWithFrame:CGRectMake(13, 15, 290, 25)];
    titleLB.text = @"领取奖品";
    [bgView2 addSubview:titleLB];

    for (int i = 0; i < 3; i++) {
        UIButton * btn = [XDTools getAButtonForView:bgView2 frame:CGRectMake(5+(100+5)*i, 55, 100, 40) nomalTitle:nil hlTitle:nil titleColor:nil bgColor:[UIColor clearColor] nbgImage:[NSString stringWithFormat:@"tryPay2_0%d",i+1] hbgImage:nil action:@selector(chooseOne:) target:self buttonTpye:UIButtonTypeCustom];
        [btn setImage:[UIImage imageNamed:[NSString stringWithFormat:@"tryPay2_0%d",i+4]] forState:UIControlStateSelected];
        btn.tag = 100+i;
        [btnArray addObject:btn];
    }

    [XDTools getAButtonForView:bgView2 frame:CGRectMake(15, 155, 290, 44) nomalTitle:@"确认支付" hlTitle:@"确认支付" titleColor:[UIColor whiteColor] bgColor:RGBA(241, 141, 0, 1) nbgImage:nil hbgImage:nil action:@selector(pay) target:self buttonTpye:UIButtonTypeCustom];

    self.shareView = [[XDShareView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT)];
    _shareView.delegate = self;
    [self.view addSubview:_shareView];

    [self getBanner];

}

- (void)getBanner{
    if ([XDTools NetworkReachable]){

        __weak ASIHTTPRequest * request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://www.xindaoapp.com/maodai/plugins/API.v1.0/?&a=category&m=activity&cat_id=10"]];
        [request setCompletionBlock:^{
            [XDTools hideProgress:self.contentView];
            NSDictionary *tempDic = [XDTools  JSonFromString:[request responseString]];

            if ([tempDic[@"result"] intValue] == 1) {
                NSMutableArray * imaArr = [[NSMutableArray alloc] init];
                for (NSDictionary * dic in tempDic[@"data"]) {
                    [imaArr addObject:dic[@"goods_img"]];
                }

                [headIV setTheImageUrlArray:imaArr andplaceholderImage:nil];
            }else{
                [XDTools showTips:tempDic[@"msg"] toView:self.view];
            }

        }];

        [request setFailedBlock:^{
            [XDTools hideProgress:self.contentView];
            NSLog(@"%@",request.error.description);
        }];
        [request startAsynchronous];
        [XDTools showProgress:self.contentView];
    }else{
        [XDTools showTips:brokenNetwork toView:self.contentView];
    }
}

- (void)chooseOne:(UIButton *)sender{
    for (UIButton * btn in btnArray) {
        btn.selected = NO;
        if (btn == sender) {
            btn.selected = YES;
            NSArray * arr = [NSArray arrayWithObjects:@"100",@"500",@"1500", nil];
            payAmt = arr[sender.tag - 100];

            headIV.myScrollView.contentOffset = CGPointMake((sender.tag-100+1)*320, 0);
        }

    }
    
}

- (void)pay{
    if (!(payAmt.intValue > 0)) {
        [XDTools showTips:@"请选择商品" toView:self.view];
        return;
    }

    if (!ISLOGING) {
        LoginViewController * login = [[LoginViewController alloc] init];
        login.payAmt = payAmt;
        [self.navigationController pushViewController:login animated:YES];
    }else{
        [self ruku];
    }
    
}


- (void)ruku{

    if ([XDTools NetworkReachable]){
        //        NSString *body = [NSString stringWithFormat:@" <ActivityList xmlns=\"http://tempuri.org/\">"
        //                          "</ActivityList>"];
        NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
        NSTimeInterval a=[dat timeIntervalSince1970]*1000;
        NSString *timeString = [NSString stringWithFormat:@"%f", a];


        NSDictionary * dic = @{@"merId":@"1000002084",
                               @"merOrderNo": timeString,         //商户订单号
                               @"merUserId": @"test",          //商户ID
                               @"notifyUrl": @"http://124.193.184.94",         ////异步回调地址
                               @"opCode": @"33A10H",             //交易码  入库33A10H
                               @"orderDesc": @"0123",          //描述
                               @"orderType":@"",
                               @"payAmt": payAmt,
                               @"productId":@"100006",
                               @"returnUrl":@"http://124.193.184.94",
                               @"userId":@""};

        NSArray * arr = [NSArray arrayWithObjects:@"merId",@"merOrderNo",@"merUserId",@"notifyUrl",@"opCode",@"orderDesc",@"orderType",@"payAmt",@"productId",@"returnUrl",@"userId", nil];


        __weak ASIHTTPRequest * request = [XDTools getRequestWithDict:dic array:arr];
        [request setCompletionBlock:^{
            [XDTools hideProgress:self.contentView];
            NSString *responseString = [request responseString];
            DDLOG(@"responseString:%@", responseString);

            if ([responseString rangeOfString:@"000000"].length == 6) {
                //保存paytoken
                NSRange range = [responseString rangeOfString:@"orderNo="];
                orderNo = [responseString substringWithRange:NSMakeRange(range.location + range.length, 20)];
                [self jiaoyan];
            }else{
                [XDTools showTips:@"订单入库失败" toView:self.view];
            }


        }];

        [request setFailedBlock:^{
            [XDTools hideProgress:self.contentView];
            NSLog(@"%@",request.error.description);
        }];
        [request startAsynchronous];
        [XDTools showProgress:self.contentView];
    }else{
        [XDTools showTips:brokenNetwork toView:self.contentView];
    }
}


- (void)jiaoyan{
    if ([XDTools NetworkReachable]){
        //校验
        NSString * userId = [[NSUserDefaults standardUserDefaults] objectForKey:kMMyUserInfo][0];

        NSDictionary * dic = @{@"cpuSerial":@"cpu12323232",
                               @"idNo":@"110108198703126311",                         //身份证
                               @"imei":@"imei32323232",
                               @"imsi":@"imsi123333",
                               @"macAddr":@"mac123",
                               @"merId":@"1000002084",
                               @"merVerifyCodeFlag": @"0",
                               @"opCode": @"28AC0H",             //交易码  入库33A10H                 1
                               @"orderNo": orderNo,
                               @"userId":userId,
                               @"userIp":@"192.168.1.2"};

        DDLOG(@"dic ::::::  %@",dic);

        NSArray * arr = [NSArray arrayWithObjects:@"cpuSerial",@"idNo",@"imei",@"imsi",@"macAddr",@"merId",@"merVerifyCodeFlag",@"opCode",@"orderNo",@"userId",@"userIp", nil];


        __weak ASIHTTPRequest * request = [XDTools getRequestWithDict:dic array:arr];
        [request setCompletionBlock:^{
            [XDTools hideProgress:self.contentView];
            NSString *responseString = [request responseString];

            DDLOG(@"jiaoyan  responseString:%@", responseString);
            if ([responseString rangeOfString:@"000000"].length == 6) {
                //保存paytoken
                NSRange range = [responseString rangeOfString:@"payToken="];
                payToken = [responseString substringWithRange:NSMakeRange(range.location + range.length, 36)];
                [self zhifu];
            }else{
                [XDTools showTips:@"风险校验失败" toView:self.view];
            }


            //            if (!isFirst) {
            //                [self secondGetCode];
            //            }
            //
            //            isFirst = NO;
        }];

        [request setFailedBlock:^{
            [XDTools hideProgress:self.contentView];
            NSLog(@"%@",request.error.description);
        }];
        [request startAsynchronous];
        [XDTools showProgress:self.contentView];
        
        
    }else{
        [XDTools showTips:brokenNetwork toView:self.contentView];
    }
}

- (void)zhifu{
    if ([XDTools NetworkReachable]){
        //        NSString *body = [NSString stringWithFormat:@" <ActivityList xmlns=\"http://tempuri.org/\">"
        //                          "</ActivityList>"];

        if (!payToken.length) {
            [XDTools showTips:@"请先获取验证码" toView:self.view];
            return;
        }

        NSString * userId = [[NSUserDefaults standardUserDefaults] objectForKey:kMMyUserInfo][0];


        NSDictionary * dic = @{@"authCode":userId,
                               @"merId":@"1000002084",
                               @"opCode": @"34AC0H",             //交易码  入库33A10H                 1
                               @"payToken": payToken};             //

        NSArray * arr = [NSArray arrayWithObjects:@"authCode",@"merId",@"opCode",@"payToken", nil];


        __weak ASIHTTPRequest * request = [XDTools getRequestWithDict:dic array:arr];
        [request setCompletionBlock:^{
            [XDTools hideProgress:self.contentView];
            NSString *responseString = [request responseString];
            DDLOG(@"zhifu responseString:%@", responseString);

            if ([responseString rangeOfString:@"000000"].length == 6) {
                [XDTools showTips:@"信用支付成功" toView:self.view];
                [self performSelector:@selector(backPrePage) withObject:nil afterDelay:0.5];
            }else{
                [XDTools showTips:@"信用支付失败" toView:self.view];
            }

        }];

        [request setFailedBlock:^{
            [XDTools hideProgress:self.contentView];
            NSLog(@"%@",request.error.description);
        }];
        [request startAsynchronous];
        [XDTools showProgress:self.contentView];
    }else{
        [XDTools showTips:brokenNetwork toView:self.contentView];
    }
}

#pragma mark ================分享按钮点击===================
-(void)shareBtnClick
{
    [_shareView setViewShow];
    DDLOG_CURRENT_METHOD;
}

#pragma mark ===============xdshareview delegate==========
-(void)shareViewBtnCLick:(UIButton *)button
{
    if (button.tag == 1001){
        [[UMSocialControllerService defaultControllerService] setShareText:@"喵贷，青春专属信贷应用，一次购物分期支付，不会再错那些让你心动不已的ta！快来用你的诚信为自己送一份礼物吧！要了解更多详情请点击：（详情链接）" shareImage:[UIImage imageNamed:@"Icon"] socialUIDelegate:self];
        [UMSocialData defaultData].extConfig.title = @"喵贷信用支付";
        [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina].snsClickHandler(self,[UMSocialControllerService defaultControllerService],YES);
    }else{
        //朋友圈分享
        [[UMSocialControllerService defaultControllerService] setShareText:@"喵贷，青春专属信贷应用，一次购物分期支付，不会再错那些让你心动不已的ta！快来用你的诚信为自己送一份礼物吧！要了解更多详情请点击：（详情链接）" shareImage:[UIImage imageNamed:@"Icon"] socialUIDelegate:self];
        [UMSocialData defaultData].extConfig.title = @"喵贷信用支付";
        [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToWechatTimeline].snsClickHandler(self,[UMSocialControllerService defaultControllerService],YES);
    }
}

- (void)backPrePage{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
